package com.lemon.tuvi2015.util;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.LabeledIntent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.MeasureSpec;
import android.widget.Toast;

import com.google.android.gms.plus.PlusShare;
import com.lemon.tuvi2015.ZodiacDetailsActivity;
import com.lemon.tuvi2015.object.GlobalObject;

public class BaseEngine {

	public static boolean isConnectionAvailable(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivityManager != null) {
			NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
			if (netInfo != null && netInfo.isConnected() && netInfo.isConnectedOrConnecting() && netInfo.isAvailable()) {
				return true;
			}
		}
		return false;
	}

	public static void shareTextUrl(Context context, String name, String url) {
		Intent share = new Intent(android.content.Intent.ACTION_SEND);
		share.setType("text/plain");
		share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
		share.putExtra(Intent.EXTRA_SUBJECT, name);
		share.putExtra(Intent.EXTRA_TEXT, url);
		context.startActivity(Intent.createChooser(share, "Share link!"));
	}

//	public static void shareBitmap(Context context, Bitmap bitmap) {
//		String pathofBmp = Images.Media.insertImage(context.getContentResolver(), bitmap, "title", null);
//		Uri bmpUri = Uri.parse(pathofBmp);
//		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
//		shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
//		shareIntent.setType("image/png");
//		context.startActivity(Intent.createChooser(shareIntent, "Share!"));
//	}
	public static void shareBitmap(Context context, Bitmap bitmap) {
//		String pathofBmp = Images.Media.insertImage(context.getContentResolver(), bitmap, "title", null);
//		Uri bmpUri = Uri.parse(pathofBmp);
//		Share(context,getShareApplication(), bmpUri);
		shareTextUrl(context, "Tử vi 360", "http://tuvi360.vn/");
	}
	
    private static List<String> getShareApplication(){
        List<String> mList=new ArrayList<String>();
        mList.add("com.facebook.katana");
        mList.add("com.twitter.android");
        mList.add("com.google.android.gm");
        mList.add("com.zing.zalo");
        return mList;

    }
    @SuppressLint("DefaultLocale") 
    private static void Share(Context context,List<String> PackageName,Uri bmpUri) {
        try
        {
        	List<Intent> targetedShareIntents = new ArrayList<Intent>();
            Intent share = new Intent(android.content.Intent.ACTION_SEND);
            share.setType("image/png");
            List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(share, 0);
            if (!resInfo.isEmpty()){
                for (ResolveInfo info : resInfo) {
                    Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
                    targetedShare.setType("image/png");
                    if (PackageName.contains(info.activityInfo.packageName.toLowerCase())) {
                        targetedShare.putExtra(Intent.EXTRA_STREAM, bmpUri);
                        targetedShare.setPackage(info.activityInfo.packageName.toLowerCase());
                        targetedShareIntents.add(targetedShare);
                    }
                }
                try {
                	Intent intent = new Intent(Intent.ACTION_SEND);
                	intent.setData(bmpUri);
                	intent.setPackage("com.google.android.apps.plus");
                	targetedShareIntents.add(intent);
				} catch (Exception e) {
					Log.e("PlusShare", "PlusShare"+e.toString());
					e.printStackTrace();
				}
                Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Share");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
                context.startActivity(chooserIntent);
            }
        }
        catch(Exception e){
             e.printStackTrace();
         }
    }
	public static void shareBitmap(Context context, Bitmap bitmap, String url) {
		String pathofBmp = Images.Media.insertImage(context.getContentResolver(), bitmap, "title", null);
		Uri bmpUri = Uri.parse(pathofBmp);
		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
		shareIntent.putExtra(Intent.EXTRA_TEXT, url);
		shareIntent.setType("*/*");
		context.startActivity(Intent.createChooser(shareIntent, "Share!"));
	}

	@TargetApi(Build.VERSION_CODES.FROYO)
	public static final void getKeyHashes(Context context) {
		PackageInfo packageInfo;
		try {
			// packageInfo =
			// getPackageManager().getPackageInfo("casino.vn",PackageManager.GET_SIGNATURES);
			packageInfo = context.getPackageManager().getPackageInfo(context.getPackageManager().getPackageInfo(context.getPackageName(), 0).packageName,
					PackageManager.GET_SIGNATURES);
			for (Signature signature : packageInfo.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				String key = new String(Base64.encode(md.digest(), 0));
				// String key = new String(Base64.encodeBytes(md.digest()));
				Log.e("Hash key", key);
			}
		} catch (NameNotFoundException e1) {
			Log.e("Name not found", e1.toString());
		} catch (NoSuchAlgorithmException e) {
			Log.e("No such an algorithm", e.toString());
		} catch (Exception e) {
			Log.e("Exception", e.toString());
		}
	}

	public static void sendSMS(Context context, String phoneNumber, String message) {
		Log.i("Send SMS", "");
		Intent smsIntent = new Intent(Intent.ACTION_VIEW);
		smsIntent.setType("vnd.android-dir/mms-sms");
		// smsIntent.setData(Uri.parse("smsto:"));
		smsIntent.putExtra("address", phoneNumber);
		smsIntent.putExtra("sms_body", message);
		try {
			context.startActivity(smsIntent);
			Log.i("Finished sending SMS...", "");
		} catch (android.content.ActivityNotFoundException ex) {
			Toast.makeText(context, "SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
		}
	}

	public static void sendSMS(Context context, String message) {
		Log.i("Send SMS", "");
		Intent smsIntent = new Intent(Intent.ACTION_VIEW);
		smsIntent.setType("vnd.android-dir/mms-sms");
		// smsIntent.setData(Uri.parse("smsto:"));
		smsIntent.putExtra("sms_body", message);
		try {
			context.startActivity(smsIntent);
			Log.i("Finished sending SMS...", "");
		} catch (android.content.ActivityNotFoundException ex) {
			Toast.makeText(context, "SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
		}
	}

	public static void showLogformLongString(String _tag, String str) {
//		String tag = "GetJson";
//		if (_tag != null && !_tag.equals("")) {
//			tag = _tag;
//		}
//		if (str != null)
//			if (str.length() > 4000) {
//				Log.e(tag, "str.length = " + str.length());
//				int chunkCount = str.length() / 4000; // integer division
//				for (int i = 0; i <= chunkCount; i++) {
//					int max = 4000 * (i + 1);
//					if (max >= str.length()) {
//						Log.e(tag, "chunk " + i + " of " + chunkCount + ":" + str.substring(4000 * i));
//					} else {
//						Log.e(tag, "chunk " + i + " of " + chunkCount + ":" + str.substring(4000 * i, max));
//					}
//				}
//			} else {
//				Log.e(tag, str.toString());
//			}
	}

	public static void startDetailsActivityObject(final Activity activity, final GlobalObject item) {
		Intent intent = new Intent(activity, ZodiacDetailsActivity.class);
		intent.putExtra(TagName.OBJ, item);
		activity.startActivity(intent);
	}

	public static void startDetailsActivityObject(final Activity activity, final GlobalObject item, String title) {
		Intent intent = new Intent(activity, ZodiacDetailsActivity.class);
		intent.putExtra(TagName.OBJ, item);
		intent.putExtra(TagName.TITLE, title);
		activity.startActivity(intent);
	}

	public static void startDetailsActivityObject_Key(final Activity activity, final GlobalObject item, final String key) {
		Intent intent = new Intent(activity, ZodiacDetailsActivity.class);
		intent.putExtra(TagName.OBJ, item);
		intent.putExtra(TagName.KEY, key);
		activity.startActivity(intent);
	}

	@SuppressWarnings("deprecation")
	public static Bitmap ConvertViewtoBitmap(Context context, View view) {
		Paint paint = new Paint();
		Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
		int width = display.getWidth(); // deprecated
		int height = display.getHeight();

		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		paint.setDither(true);
		Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bmp);
		view.setDrawingCacheEnabled(true);
		view.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(canvas.getHeight(), MeasureSpec.EXACTLY));
		view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
		canvas.drawBitmap(view.getDrawingCache(), 0, 0, paint);
		view.setDrawingCacheEnabled(false);
		return bmp;
	}

}
